Ext.onReady(function(){ 

Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'under';

var record_start = 0; 

var sm = new Ext.grid.CheckboxSelectionModel();
var cm=new Ext.grid.ColumnModel([ 
sm,
new Ext.grid.RowNumberer({header: "编号",width:40,
	renderer:function(value,metadata,record,rowIndex){ 
return record_start + 1 + rowIndex; 
} 
}),

{header:'流水号',dataIndex:'serialNo',hidden:true},
{header:'地址类型',dataIndex:'addressType',width:100},
{header:'国家',dataIndex:'countryCode',width:100},
{header:'省份',dataIndex:'provinceCode',width:100}, 
{header:'城市',dataIndex:'cityCode',width:100},
{header:'街道详情',dataIndex:'addressDesc',width:100},
{header:'邮编',dataIndex:'postCode',width:100},
{header:'电话',dataIndex:'tel',width:100},
{header:'传真',dataIndex:'fax',width:100},
{header:'网址',dataIndex:'webSiteUrl',width:100},
]); 
var ds=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'customer/listAddress.do',
method:'POST'
}), 
reader:new Ext.data.JsonReader(
{ totalProperty:'total',  
	root:'address'},
[{name:'serialNo'},
{name:'addressType'}, 
{name:'countryCode'},  
{name:'provinceCode'},  
{name:'cityCode'},  
{name:'addressDesc'},  
{name:'postCode'},  
{name:'tel'},  
{name:'fax'},  
{name:'webSiteUrl'}
]) 
}); 
ds.load({params:{start:0,limit:20}}); 

var addTypeStore=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'showType.do?type=AddressType',
method:'GET'
}), 
reader:new Ext.data.JsonReader({ },[
{name:'name'}, 
{name:'code'}
]) ,
autoLoad: true
}); 

var countryStore=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'showCountry.do',
method:'POST'
}), 
reader:new Ext.data.JsonReader({ },[
{name:'name'}, 
{name:'code'}
]) 
}); 
countryStore.load();

var provinceStore = new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'showProvince.do',
method:'GET'
}), 
reader:new Ext.data.JsonReader({ },[
{name:'provinceCode'}, 
{name:'provinceName'}
]) 
}); 
provinceStore.load();

 var cityStore = new Ext.data.Store({ 
				reader:new Ext.data.JsonReader({ },[
				{name:'cityCode'}, 
				{name:'cityName'}
				]) 
				});

var grid=new Ext.grid.GridPanel({ 
id:'myCustomers',
renderTo:"customer_list", 
stripeRows:true,//斑马线效果
title:"客户地址列表", 
height:500, 
cm:cm,
store: ds,
loadMask: { msg: "加载中..." }, 
viewConfig: {   
                            forceFit:true   
            },   
            bbar: new Ext.PagingToolbar({   
                pageSize: 20,   
                store: ds, 
                displayInfo: true,   
                displayMsg: '第{0} 到 {1} 条数据 共{2}条',   
                emptyMsg: "没有数据"   ,
                doLoad : function(start){ 
                	   record_start = start; 
                	var o = {}, pn = this.getParams(); 
                	          o[pn.start] = start; 
                	          o[pn.limit] = this.pageSize; 
                	this.store.load({params:o}); 
                }
            }),
 tbar: [
 {text:'新增',id: 'btnAdd'},
 '-',
 {text:'查看/编辑',handler:checkMyCustomer},
 '-',
 {text:'删除',handler:deleteCustomer}
 ]              
});

//新增客户表单
addForm = new Ext.form.FormPanel({ 
id: 'addCustomerForm', 
width: 480, 
height: 300, 
//样式 
bodyStyle: 'margin:3px 3px 3px 3px', 
frame: true, 
xtype: 'filedset', 
labelWidth: 60, 
items: 
[ { xtype: 'fieldset', 
title: '地址信息', 
collapsible: true, 
autoHeight: true, 
autoWidth: true, 
items: 
[ { layout : "form",
           items : [{
xtype: 'combo', 
 id : "addressType",
              store :addTypeStore,
              fieldLabel: '地址类型',
              valueField : 'code',
              displayField : 'name',
              emptyText : '请选择地址类型...',
              allowBlank : false,
              blankText:'请选择地址类型',
              editable: false,
              typeAhead : true,
              width: 130,
              mode:'remote', 
              hiddenName:'addressType',
              triggerAction : 'all',
              selectOnFocus : true 
}]},{ layout : "form",
           items : [{
xtype: 'combo', 
 id : "countryCode",
              store :countryStore,
              fieldLabel: '国家',
              valueField : 'code',
              displayField : 'name',
              emptyText : '请选择国家...',
              editable: false,
              allowBlank : false,
              typeAhead : true,
              width: 130,
              mode:'remote',  
              hiddenName:'countryCode',
              triggerAction : 'all',
              selectOnFocus : true,
              value: "materCode",
              listeners:{        
                  select : function(combo, record,index)   
                  {   
       			var cityCombo = Ext.getCmp('cityCode');
       			var provinceCombo = Ext.getCmp('provinceCode');
               
                if(combo.value=='109'){
                	provinceCombo.enable();
                	cityCombo.enable();
                }else{
                	provinceCombo.clearValue(); 
                	cityCombo.clearValue(); //可以实现当下拉值变更时，清空之前下拉选项中的值   
                	provinceCombo.disable();
                	cityCombo.disable();
                }
                
              }
            }
              
}]},{
	layout:"column",
items:[{
	columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
        	   xtype: 'combo', 
        	   id : "provinceCode",
              store :provinceStore,
              fieldLabel: '省份',
              valueField : 'provinceCode',
              displayField : 'provinceName',
              typeAhead : true,
              width: 130,
              mode:'remote', 
              emptyText : '请选择省份...',
              editable: false,
              triggerAction : 'all',
              selectOnFocus : true,
              hiddenName:'provinceCode',
               listeners:{        
        	   select : function(combo, record,index)   
        	   {   
        	   		var cityCombo = Ext.getCmp('cityCode');
        	   		cityCombo.clearValue(); //可以实现当下拉值变更时，清空之前下拉选项中的值   
//               alert(combo.value);
        	   		cityStore.proxy =new Ext.data.HttpProxy({
        	   				url:'showCity.do?provinceId='+combo.value,
        	   				method:'GET'
        	   		});
			
                  
        	   		cityStore.load(); //加载下拉框的store      
        	   }      
           }
}]},
{ columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
        	   xtype: 'combo', 
        	   id : "cityCode",
              store :cityStore,
            fieldLabel: '城市',
              valueField : 'cityCode',
              displayField : 'cityName',
              emptyText : '请选择城市...',
              editable: false,
              typeAhead : true,
              width: 130,
              mode:'remote',  
              triggerAction : 'all',
              selectOnFocus : true,
              hiddenName:'cityCode'
         
}]} 
]}, { layout : "form",
           items : [{
xtype: 'textfield',
id: 'addressDesc', 
name: 'addressDesc', 
fieldLabel: '街道详情', 
emptyText: '必填', 
blankText: '街道详情不能为空', 
allowBlank: false,  
anchor: '96%' 
}]},{
	layout:"column",
	items:[{
		columnWidth: .5,// 该列有整行中所占百分比
		layout : "form",
        items : [{
				xtype: 'textfield',
				id: 'postCode', 
				name: 'postCode', 
				fieldLabel: '邮编',
				allowBlank: true,     
				width: 130 
        }]
	},{
		columnWidth : .5, // 该列有整行中所占百分比
	       layout : "form",
	       items : [{
				xtype: 'textfield',
				id: 'tel', 
				name: 'tel', 
				fieldLabel: '电话',
				regex:/^\d+$/ ,
	            allowBlank : false,             
				allowNegative:false,  
				width: 130 
	           }]
	}]
},
 { },{
	layout:"column",
	items:[{
		columnWidth : .5, // 该列有整行中所占百分比
       layout : "form",
       items : [{
			xtype: 'textfield',
			id: 'telFinan', 
			name: 'telFinan', 
			fieldLabel: '财务电话',
            allowBlank : false,             
			allowNegative:false,  
			width: 130 
           }]
       },{ 
        columnWidth : .5, // 该列有整行中所占百分比
           layout : "form",
           items : [{
xtype: 'textfield',
id: 'fax', 
name: 'fax', 
fieldLabel: '传真',
allowBlank: true,           
allowNegative:false, 
width: 130 
}]} 
]},{ layout : "form",
           items : [{
xtype: 'textfield',
id: 'webSiteUrl', 
name: 'webSiteUrl', 
fieldLabel: '网址',  
allowBlank: true,  
anchor: '96%' 
}]},
{ layout : "form",
           items : [{
xtype: 'hidden', 
 id : "serialNo",
              fieldLabel: '地址ID',
              allowBlank: true
}]}
]}]});

//新增用户窗口 
addWin = new Ext.Window({ 
id: 'addCustomerWin', 
title: '新增客户-地址', 
width: 500, 
height: 350, 
//背景遮罩 
modal: true, 
//重置大小 
resizable: false, 
//当关闭按钮被点击时执行的动作 
closeAction: 'hide', 
plain: true, 
buttonAlign: 'right', 
items:addForm, 
buttons: 
[  
{ text: '保存', id: 'btnSubmit' } ,
{ text: '关闭', handler: function() { Ext.getCmp('addCustomerWin').hide(); } }

] 
});

var config={
    title:"提示",
    width:240,
    msg:'<div align="center">添加成功！</div>',
    closable:false,
    buttons:{cancel:'取消',yes:'下一步',no:'继续添加地址'},
    fn: function(btn){
    	if(btn == 'yes'){
			window.location.href='view/customer/Customer_Operation.jsp';
    	}

    	else if(btn == 'no'){
    		btnAddClick();
    	}
    }
    //icon:Ext.MessageBox.Question
}

function addRoleFunction() {

	var addForm = Ext.getCmp("addCustomerForm");
	if(addForm.form.isValid()){

	 addForm.form.doAction('submit', { 

                    url : 'customer/addAddress.do', 
 
                    method : 'post', 
 
                       
                       success : function() { 

                      var msgbox = Ext.MessageBox.show(config); 
                       Ext.getCmp('addCustomerWin').hide();
                       Ext.getCmp('myCustomers').store.reload();
                      Ext.Msg.alert('提示', '保存成功！'); 
 
                       }, 
                        failure : function(form, action) { 

                           Ext.Msg.alert('提示', '保存失败！'); 
 
                        } 
                    });  
                    }
 }
  


//添加按钮单击事件 
function btnAddClick() { 
Ext.getCmp("addCustomerWin").show();
addForm.getForm().getEl().dom.reset(); 
Ext.getCmp("addCustomerWin").hide(); 

Ext.getCmp("addCustomerWin").buttons[0].handler = addRoleFunction; 
Ext.getCmp("addCustomerWin").show(); 
}; 

//新增按钮 
var addUserBtn = Ext.getCmp('btnAdd'); 
addUserBtn.on('click', btnAddClick); 

//删除地址
function deleteCustomer(){
var grid = Ext.getCmp('myCustomers'); 
if (grid.getSelectionModel().getSelections()[0] == undefined) { 
Ext.Msg.alert("提示", "请选中要删除的地址！"); 
} 
else{
Ext.MessageBox.confirm('提示', '确实要删除所选的地址吗？', deleteConfirm);
}
}

function deleteConfirm(btn){
if (btn == 'yes') {
//alert(grid.getSelectionModel().getSelections()[0].data.serialNo);
 Ext.Ajax.request({
  url:'customer/deleteAddress.do',
  params : { serialNo: grid.getSelectionModel().getSelections()[0].data.serialNo},
  method:'POST',
  success:function(){
   Ext.MessageBox.alert("提示","删除成功！");
   Ext.getCmp('myCustomers').store.reload(); 
  },failure:function(){
    Ext.MessageBox.alert("提示", "删除失败！"); 
  }
});
}
}

//编辑地址
function editAddressFunction(){
	
	var addForm = Ext.getCmp("addCustomerForm");

if(addForm.form.isValid()){
	 addForm.form.doAction('submit', { 

                    url : 'customer/editAddress.do', 
 
                    method : 'post', 
 
                       
                       success : function() { 

                       
                       Ext.getCmp('myCustomers').store.reload();
                       Ext.Msg.alert('提示', '编辑地址成功！'); 
 
                       }, 
                        failure : function(form, action) { 

                           Ext.Msg.alert('提示', '编辑地址失败！'); 
 
                        } 
                    }); 
                    }
}

function checkMyCustomer(){
if (grid.getSelectionModel().getSelections()[0] == undefined) { 
Ext.Msg.alert("提示", "请选中要编辑的地址！"); 
}
else{
	var serialNo = grid.getSelectionModel().getSelections()[0].data.serialNo;
	
	Ext.getCmp('addCustomerForm').form.reset(); 
	Ext.getCmp("addCustomerWin").buttons[0].handler = editAddressFunction; 

	Ext.Ajax.request({
url:'customer/getAddress.do',
params : { serialNo: grid.getSelectionModel().getSelections()[0].data.serialNo},
method:'POST',
  success:function(response){
 // alert(response.responseText);
 var addJSON = Ext.util.JSON.decode(response.responseText);
 
 //加载当前省份的城市列表
	cityStore.proxy=new Ext.data.HttpProxy({
		url:'showCity.do?provinceId='+addJSON.provinceCode,
		method:'GET'
	});
	cityStore.load();
	
  	Ext.getCmp("serialNo").setValue(addJSON.serialNo);
	Ext.getCmp("addressType").setValue(addJSON.addressType);
  	Ext.getCmp("countryCode").setValue(addJSON.countryCode);
	Ext.getCmp("provinceCode").setValue(addJSON.provinceCode);
   	Ext.getCmp("cityCode").setValue(addJSON.cityCode);
	Ext.getCmp("addressDesc").setValue(addJSON.addressDesc);
	Ext.getCmp("postCode").setValue(addJSON.postCode);
  	Ext.getCmp("tel").setValue(addJSON.tel);
  	Ext.getCmp("telFinan").setValue(addJSON.telFinan);
  	Ext.getCmp("fax").setValue(addJSON.fax);
  	Ext.getCmp("webSiteUrl").setValue(addJSON.webSiteUrl);
  	
  	var cityCombo = Ext.getCmp('cityCode');
		var provinceCombo = Ext.getCmp('provinceCode');

    if(addJSON.countryCode=='109'){
    	provinceCombo.enable();
    	cityCombo.enable();
    }else{
    	provinceCombo.clearValue(); 
    	cityCombo.clearValue(); //可以实现当下拉值变更时，清空之前下拉选项中的值   
    	provinceCombo.disable();
    	cityCombo.disable();
    }
  	
	Ext.getCmp("addCustomerWin").show(); 
	
	
  },failure:function(){
    Ext.MessageBox.alert("请求异常！");
  }
}); 

/*	var addressStore = new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'customer/getAddress.do?serialNo='+serialNo,
method:'POST'
}), 
reader:new Ext.data.JsonReader({ },[
{name:'addressType'}, 
{name:'countryCode'},  
{name:'provinceCode'},  
{name:'cityCode'},  
{name:'addressDesc'},  
{name:'postCode'},  
{name:'tel'},  
{name:'fax'},  
{name:'webSiteUrl'}
]) 
}); 
addressStore.load();

var record = addressStore.data.items[0];
alert(record);
Ext.getCmp("addressDesc").setValue(record.addressDesc);
 */

}
}

function rowdblclickFn(grid, rowIndex, e){//双击事件  
             var row = grid.getStore().getAt(rowIndex); 
             var selectedCustId = row.get("custId");
             Ext.Ajax.request({
  url:'checkRequest.do',
  method:'GET',
  success:function(){
  window.location.href="checkMyCustomer.do?CustId="+selectedCustId;
  },failure:function(){
    Ext.MessageBox.alert("请求异常！");
  }
});  
           //  window.location.href="view/customer/CheckCustomer_General.jsp?custId="+selectedCustId;
        }   
        grid.addListener('rowdblclick',checkMyCustomer);
/*grid.on('rowdblclick',function(){ window.location.href="view/customer/CheckCustomer_General.jsp" });*/
}); 